from datetime import date, datetime, timedelta, timezone

from django.db import transaction
from django.shortcuts import render
from django.db.models import Count, Max, Min
from django.core.exceptions import ObjectDoesNotExist

# Create your views here.

from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework import status
from rest_framework import filters
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema, coreapi
from coreapi import Field
import coreschema
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from ephm_mqtt_data_push.utils import clear_tolerance_cache, update_tolerance_cache

from django_filters.rest_framework import DjangoFilterBackend

from .models import *
from .serializers import *


from django.db.models import Q
import json
import re
import importlib

from rest_framework.schemas.coreapi import AutoSchema
import coreapi

from dateutil import parser

SERIALIZER_MODULE = "ephm_api.serializers"
MODULES = "ephm_api.models"


class ephm_warning_viewset(APIView):
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="area",  # CB
                required=False,
                location="query",
                schema=coreschema.String(description="测点所属区域"),
            ),
            Field(
                name="location",  # cb1op1001-SP_LOAD
                required=False,
                location="query",
                schema=coreschema.String(description="测点所属设备及测点名称"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):

        warning_list = self.get_queryset(request)
        serializer = warning_serializer(warning_list, many=True)
        if warning_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        queryset = warning.objects.all()

        # 按区域精准查询测点台账
        area = request.query_params.get("area", None)
        print(area)
        if area is not None:
            queryset = queryset.filter(area=area)
        else:
            print("no area")

        # 按测点内容模糊查询测点台账
        location = request.query_params.get("location", None)
        print(location)
        if location is not None:
            queryset = queryset.filter(Q(location__icontains=location))
        else:
            print("no location")

        return queryset


class data_hour_viewset(APIView):
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="station",  # CB1OP201
                required=False,
                location="query",
                schema=coreschema.String(description="测点所属设备"),
            ),
            Field(
                name="item",  # tm_tlopen
                required=False,
                location="query",
                schema=coreschema.String(description="测点名称"),
            ),
            Field(
                name="area",  # CB
                required=False,
                location="query",
                schema=coreschema.String(description="测点所属区域"),
            ),
            Field(
                name="start_time",
                required=True,
                location="query",
                schema=coreschema.String(description="起始时间"),
            ),
            Field(
                name="end_time",
                required=True,
                location="query",
                schema=coreschema.String(description="结束时间"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):

        data_hour_list = self.get_queryset(request)
        serializer = data_hour_serializer(data_hour_list, many=True)
        if data_hour_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        queryset = data_hour.objects.all().order_by("-time")

        station = request.query_params.get("station", None)
        item = request.query_params.get("item", None)
        area = request.query_params.get("area", None)

        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        if (start_time_param and end_time_param) is None:
            queryset = data_hour.objects.none()
        else:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(time__gte=start_time_param_trans, time__lte=end_time_param_trans)

        # 按区域模糊查询测点台账————区域会分模块，比如cb1，cb2，ch1，ch2
        if area is not None:
            queryset = queryset.filter(Q(area__icontains=area))
        else:
            print("no area")

        # 按测点内容模糊查询测点台账
        if station is not None:
            queryset = queryset.filter(Q(station__icontains=station))
        else:
            print("no station")

        # 按测点名称模糊查询测点台账
        if item is not None:
            queryset = queryset.filter(Q(item__icontains=item))
        else:
            print("no item")

        return queryset


class oil_level_viewset(APIView):
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="station",  # CBM1OP201
                required=False,
                location="query",
                schema=coreschema.String(description="测点所属设备"),
            ),
            Field(
                name="item",  # oil_leve  oil_delta
                required=False,
                location="query",
                schema=coreschema.String(description="测点名称"),
            ),
            Field(
                name="start_time",
                required=True,
                location="query",
                schema=coreschema.String(description="起始时间"),
            ),
            Field(
                name="end_time",
                required=True,
                location="query",
                schema=coreschema.String(description="结束时间"),
            ),
        ],
    )

    def get(self, request, *args, **kwargs):

        oil_level_list = self.get_queryset(request)
        serializer = oil_level_serializer(oil_level_list, many=True)
        if oil_level_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        queryset = oil_level.objects.all()

        # 按区域模糊查询测点台账————区域会分模块，比如cb1，cb2，ch1，ch2
        station = request.query_params.get("station", None)
        item = request.query_params.get("item", None)

        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        if (start_time_param and end_time_param) is None:
            queryset = oil_level.objects.none()
        else:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(time__gte=start_time_param_trans, time__lte=end_time_param_trans)

        # 按设备名称模糊查询测点台账
        if station is not None:
            queryset = queryset.filter(Q(station__icontains=station))
        else:
            print("no station")

        # 按液位、液位差模糊查询测点台账
        if item is not None:
            queryset = queryset.filter(Q(item__icontains=item))
        else:
            print("no item")

        return queryset


class cb2op201_viewset(APIView):  # 已并入cnc_api，不再使用
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="start_time",
                required=True,
                location="query",
                schema=coreschema.String(description="起始时间"),
            ),
            Field(
                name="end_time",
                required=True,
                location="query",
                schema=coreschema.String(description="结束时间"),
            ),
            Field(
                name="tool_num",
                required=False,
                location="query",
                schema=coreschema.String(description="刀具编号"),
            ),
            Field(
                name="nc_num",
                required=False,
                location="query",
                schema=coreschema.String(description="NC程序"),
            ),
        ],
    )

    def get(self, request, *args, **kwargs):

        cb2op201_list = self.get_queryset(request)
        serializer = cb2op201_serializer(cb2op201_list, many=True)
        if cb2op201_list:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        queryset = cb2op201.objects.all().filter()

        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        tool_num = request.query_params.get("tool_num", None)
        NC_num = request.query_params.get("nc_num", None)

        if (start_time_param and end_time_param) is None:
            queryset = cb2op201.objects.none()
        else:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(time__gte=start_time_param_trans, time__lte=end_time_param_trans)

        if tool_num is not None:
            queryset = queryset.filter(Q(t_no__icontains=tool_num))
        else:
            print("no tool_num")

        if NC_num is not None:
            queryset = queryset.filter(Q(nc_prg__icontains=NC_num))
        else:
            print("no NC_num")

        return queryset


class cnc_viewset(APIView):
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="start_time",
                required=True,
                location="query",
                schema=coreschema.String(description="起始时间"),
            ),
            Field(
                name="end_time",
                required=True,
                location="query",
                schema=coreschema.String(description="结束时间"),
            ),
            Field(
                name="machine",
                required=True,
                location="query",
                schema=coreschema.String(description="设备名称,格式类似 cb1op101,精确匹配"),
            ),
            Field(
                name="tool_num",
                required=False,
                location="query",
                schema=coreschema.String(description="刀具号"),
            ),
            Field(
                name="nc_num",
                required=False,
                location="query",
                schema=coreschema.String(description="NC程序"),
            ),
        ],
    )

    def get_serializer_class(self, request, *args, **kwargs):
        machine = request.query_params.get("machine", None)
        try:
            module = importlib.import_module(SERIALIZER_MODULE)
            serializer_class = getattr(module, machine + "_serializer")
            return serializer_class
        except Exception as e:
            print("get!!!", e)
            return None

    def get(self, request, *args, **kwargs):
        serializer_class = self.get_serializer_class(request)
        if serializer_class is None:
            return Response("Invalid serializer name", status=status.HTTP_404_NOT_FOUND)
        serializer = serializer_class(self.get_queryset(request), many=True)
        if serializer:
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        machine = request.query_params.get("machine", None)
        if machine is None:
            return None

        try:
            model = getattr(importlib.import_module(MODULES), machine)
        except Exception as e:
            print("get_queryset!!!", e)
            return None

        queryset = model.objects.all()

        # 时间范围规定不为空
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        tool_num = request.query_params.get("tool_num", None)
        NC_num = request.query_params.get("nc_num", None)
        if (start_time_param and end_time_param) is None:
            queryset = model.objects.none()
        else:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(time__gte=start_time_param_trans, time__lte=end_time_param_trans)

        if tool_num is not None:
            queryset = queryset.filter(Q(t_no=tool_num))
        else:
            print("no tool_num")

        if NC_num is not None:
            queryset = queryset.filter(Q(nc_prg=NC_num))
        else:
            print("no NC_num")

        return queryset


class get_station_info_viewset(APIView):
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="api",
                required=True,
                location="query",
                schema=coreschema.String(description="接口名称,如: oil_level/data_hour/warning 等,采用模糊查询"),
            ),
            Field(
                name="area",
                required=False,
                location="query",
                schema=coreschema.String(description="区域,如: cb/ch 等,采用模糊查询"),
            ),
            Field(
                name="item",
                required=False,
                location="query",
                schema=coreschema.String(description="测点名称,如: tm_tlopen/SP_LOAD 等,采用模糊查询"),
            ),
        ],
    )

    def get(self, request, *args, **kwargs):
        station_info = self.get_queryset(request)
        if station_info:
            return Response(station_info, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        api = request.query_params.get("api", None)
        area = request.query_params.get("area", None)
        item = request.query_params.get("item", None)

        if "data_hour" in api:
            print("data_hour_api")
            if area is None and item is not None:
                station_info = data_hour.objects.filter(item__icontains=item).values("station").distinct()
                station_info = queryset_formater(station_info)

            elif item is None and area is not None:
                station_info = data_hour.objects.filter(area__icontains=area).values("station").distinct()
                station_info = queryset_formater(station_info)

            elif area is not None and item is not None:
                station_info = data_hour.objects.filter(area__icontains=area, item__icontains=item).values("station").distinct()
                station_info = queryset_formater(station_info)

            else:
                station_info = data_hour.objects.none()

        elif "oil_level" in api:
            print("oil_level_api")
            if item is not None and area is None:
                area = area_formater(area)
                station_info = oil_level.objects.filter(item__icontains=item).values("station").distinct()
                station_info = queryset_formater(station_info)

            elif item is None and area is not None:
                area = area_formater(area)
                station_info = oil_level.objects.filter(station__icontains=area).values("station").distinct()
                station_info = queryset_formater(station_info)

            elif area is not None and item is not None:
                area = area_formater(area)
                station_info = oil_level.objects.filter(station__icontains=area, item__icontains=item).values("station").distinct()
                station_info = queryset_formater(station_info)

            else:
                station_info = oil_level.objects.none()

        elif "warning" in api:
            print("warning_api")
            if area is None and item is not None:
                station_info = warning.objects.filter(location__icontains=item).values("location").distinct()
                for i in station_info:
                    i["location"] = i["location"].split("-")[0]
                station_info = queryset_formater(station_info)

            elif item is None and area is not None:
                station_info = warning.objects.filter(area__icontains=area).values("location").distinct()
                for i in station_info:
                    i["location"] = i["location"].split("-")[0]
                station_info = queryset_formater(station_info)

            elif area is not None and item is not None:
                station_info = warning.objects.filter(area__icontains=area, location__icontains=item).values("location").distinct()
                for i in station_info:
                    i["location"] = i["location"].split("-")[0]
                station_info = queryset_formater(station_info)

            else:
                station_info = warning.objects.none()

        else:
            station_info = 0

        return station_info


class get_tool_nc_viewset(APIView):
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="machine",
                required=True,
                location="query",
                schema=coreschema.String(description="设备名称,如: cb1op101,精确匹配"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        tool_nc_info = self.get_queryset(request)
        if tool_nc_info:
            return Response(tool_nc_info, status=status.HTTP_200_OK)
        else:
            return Response("No data", status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        machine = request.query_params.get("machine", None)
        if machine is None:
            return None

        try:
            model = getattr(importlib.import_module(MODULES), machine)
        except Exception as e:
            print("get_queryset!!!", e)
            return None

        queryset = model.objects.all()

        tool_info = queryset.values("t_no").distinct()
        nc_info = queryset.values("nc_prg").distinct()

        tool_nc_info = {"tool_info": tool_info, "nc_info": nc_info}

        return tool_nc_info


def queryset_formater(queryset):  # 用于格式化queryset，去重，返回为前端所需下拉框数据格式
    data = []
    for i in queryset:
        if i.keys() == {"station"}:
            record = {"value": i["station"], "label": i["station"]}
            if record not in data:
                data.append(record)
        elif i.keys() == {"location"}:
            record = {"value": i["location"], "label": i["location"]}
            if record not in data:
                data.append(record)
    return data


def area_formater(area):  # 用于格式化area
    result = ""
    char = re.sub("([^\u0041-\u007a])", "", area)
    num = re.sub("([^\u0030-\u0039])", "", area)
    print(111111, char[-1].lower(), num)

    if char[-1].lower() != "m":
        print(222222)
        if "cs" in char:
            result = char + num
        else:
            result = char + "m" + num

    elif char[-1].lower() == "m":
        print(333333)
        if "cs" in char:
            result = char[:2]
        else:
            result = char + num

    print(result)
    return result


class opInfoData(APIView):
    # 设置默认的每页数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="item",
                required=True,
                location="query",
                schema=coreschema.String(description="负载监控|压力监控|..."),
            ),
            Field(
                name="value",
                required=False,
                location="query",
                schema=coreschema.String(description="value"),
            ),
            Field(
                name="label",
                required=False,
                location="query",
                schema=coreschema.String(description="label"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = EphmOpInfoData_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = EphmOpInfoData.objects.using("ephm").all().order_by("-id")
        # 获取请求的参数
        id = request.query_params.get("id")
        item = request.query_params.get("item")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = EphmOpInfoData.objects.using("ephm").filter(id=id)
        if item is not None:
            queryset = EphmOpInfoData.objects.using("ephm").filter(item__contains=item)
        else:
            pass
        return queryset


class classListInfoData(APIView):
    # 设置默认的每页数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="item",
                required=True,
                location="query",
                schema=coreschema.String(description="动作时间监控|电流监控|液位监控|负载监控|压力监控|温度监控|..."),
            ),
            Field(
                name="value",
                required=False,
                location="query",
                schema=coreschema.String(description="value"),
            ),
            Field(
                name="label",
                required=False,
                location="query",
                schema=coreschema.String(description="label"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = EphmClassList_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = EphmClassList.objects.using("ephm").all().order_by("-id")
        # 获取请求的参数
        id = request.query_params.get("id")
        item = request.query_params.get("item")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = EphmClassList.objects.using("ephm").filter(id=id)
        if item is not None:
            queryset = EphmClassList.objects.using("ephm").filter(item=item)
        else:
            pass
        return queryset


class PowertrainOpInfoData(APIView):
    # 设置默认的每页默认数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="zone",
                required=False,
                location="query",
                schema=coreschema.String(description="区域"),
            ),
            Field(
                name="loop",
                required=False,
                location="query",
                schema=coreschema.String(description="工段"),
            ),
            Field(
                name="label",
                required=False,
                location="query",
                schema=coreschema.String(description="标签"),
            ),
            Field(
                name="value",
                required=False,
                location="query",
                schema=coreschema.String(description="值"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = PowertrainOpInfo_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = PowertrainOpInfo.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        loop = request.query_params.get("loop")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if loop is not None:
            queryset = queryset.filter(loop=loop)
        else:
            pass
        return queryset


class PowertrainProjNameData(APIView):
    # 设置默认的每页默认数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="zone",
                required=False,
                location="query",
                schema=coreschema.String(description="区域"),
            ),
            Field(
                name="loop",
                required=False,
                location="query",
                schema=coreschema.String(description="工段"),
            ),
            Field(
                name="op_number",
                required=False,
                location="query",
                schema=coreschema.String(description="工位号"),
            ),
            Field(
                name="value",
                required=False,
                location="query",
                schema=coreschema.String(description="value"),
            ),
            Field(
                name="label",
                required=False,
                location="query",
                schema=coreschema.String(description="label"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = PowertrainProjName_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = PowertrainProjName.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        loop = request.query_params.get("loop")
        op_number = request.query_params.get("opNumber")
        print(op_number)
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if loop is not None:
            queryset = queryset.filter(loop=loop)
        if op_number is not None:
            queryset = queryset.filter(op_number=op_number)
        return queryset


# 使用AutoSchema的子类来分别定义针对GET和POST方法这两种方法的schema
class CustomSchema(AutoSchema):
    def get_manual_fields(self, path, method):
        # 获取父类中已有的手动字段
        manual_fields = super().get_manual_fields(path, method)

        if method.lower() == "get":
            # 为 GET 请求添加查询参数
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="query",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="loop",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="工段"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="projname",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="项目名称"),
                ),
                Field(
                    name="value",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="数值"),
                ),
                Field(
                    name="unit",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="单位"),
                ),
                Field(name="datetime", required=False, location="query", schema=coreschema.String(description="日期时间(例如:2025-01-16 16:39:01)")),
                # 更多查询参数...
            ]
        elif method.lower() == "post":
            # 为 POST 请求设置必填项和其他选项
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="form",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="loop",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="工段"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="projname",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="项目名称"),
                ),
                Field(
                    name="value",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="数值"),
                ),
                Field(
                    name="unit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="单位"),
                ),
                Field(name="datetime", required=False, location="form", schema=coreschema.String(description="日期时间(例如:2025-01-16 16:39:01)实际录入时间+8小时")),
                # 更多表单字段...
            ]
        elif method.lower() == "patch":
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="form",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="loop",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="工段"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="projname",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="项目名称"),
                ),
                Field(
                    name="value",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="数值"),
                ),
                Field(
                    name="unit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="单位"),
                ),
                Field(name="datetime", required=False, location="form", schema=coreschema.String(description="日期时间(例如:2025-01-16 16:39:01)实际录入时间+8小时")),
                # 更多表单字段...
            ]
        return manual_fields


class PowerEphmManuEnterDataPost(APIView):
    # 设置默认的每页默认数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = CustomSchema()

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = PowerEphmManuEnterData_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        original_datetime_str = request.data["datetime"]
        # # 使用 dateutil.parser 解析字符串为 datetime 对象
        dt = parser.parse(original_datetime_str)
        # # if timezone.is_naive(dt):
        # #     dt = timezone.make_aware(dt, timezone.utc)
        # # 将GMT时间转换为CST时间
        cst_dt = dt + timedelta(hours=8)
        # # # 格式化为期望的格式字符串
        formatted_datetime_str = cst_dt.strftime("%Y-%m-%d %H:%M:%S")
        data = request.data
        data["datetime"] = formatted_datetime_str
        # # print(formatted_datetime_str)
        # # print(request.data["datetime"])
        print(data)
        serializer = PowerEphmManuEnterData_Serializer(data=data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, *args, **kwargs):
        data = request.data
        serializers = PowerEphmManuEnterData_Serializer(data=data)
        if serializers.is_valid():
            serializers.save()
            return Response(serializers.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = PowerEphmManuEnterData.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        loop = request.query_params.get("loop")
        op = request.query_params.get("op")
        projname = request.query_params.get("projname")
        op_number = request.query_params.get("opNumber")
        print(op_number)
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if loop is not None:
            queryset = queryset.filter(loop=loop)
        if op is not None:
            queryset = queryset.filter(op=op)
        if projname is not None:
            queryset = queryset.filter(projname=projname)
        return queryset


class PowerEphmManuEnterDataMainAxis(APIView):
    # 设置默认的每页默认数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = CustomSchema()

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = PowerEphmManuEnterData_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        original_datetime_str = request.data["datetime"]
        # # 使用 dateutil.parser 解析字符串为 datetime 对象
        dt = parser.parse(original_datetime_str)
        # # if timezone.is_naive(dt):
        # #     dt = timezone.make_aware(dt, timezone.utc)
        # # 将GMT时间转换为CST时间
        cst_dt = dt + timedelta(hours=8)
        # # # 格式化为期望的格式字符串
        formatted_datetime_str = cst_dt.strftime("%Y-%m-%d %H:%M:%S")
        data = request.data
        data["datetime"] = formatted_datetime_str
        # # print(formatted_datetime_str)
        # # print(request.data["datetime"])
        print(data)
        serializer = PowerEphmManuEnterData_Serializer(data=data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, *args, **kwargs):
        data = request.data
        serializers = PowerEphmManuEnterData_Serializer(data=data)
        if serializers.is_valid():
            serializers.save()
            return Response(serializers.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = PowerEphmManuEnterData.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        loop = request.query_params.get("loop")
        op = request.query_params.get("op")
        projname = request.query_params.get("item")
        op_number = request.query_params.get("station")
        print(op_number)
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if loop is not None:
            queryset = queryset.filter(loop=loop)
        if op is not None:
            queryset = queryset.filter(op=op)
        if projname is not None:
            queryset = queryset.filter(projname=projname)
        return queryset


class PowertrainMeasurementPointLedger(APIView):
    # 设置默认的每页默认数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="zone",
                required=False,
                location="query",
                schema=coreschema.String(description="区域"),
            ),
            Field(
                name="module",
                required=False,
                location="query",
                schema=coreschema.String(description="工段/模块"),
            ),
            Field(
                name="station",
                required=False,
                location="query",
                schema=coreschema.String(description="工位"),
            ),
            Field(
                name="proj_name",
                required=False,
                location="query",
                schema=coreschema.String(description="测点名称"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = PowerEphmMeasurementPointLedger_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        from django.forms.models import model_to_dict

        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = PowerEphmMeasurementPointLedger.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        module = request.query_params.get("module")
        station = request.query_params.get("station")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if module is not None:
            queryset = queryset.filter(module=module)
        if station is not None:
            queryset = queryset.filter(station=station)
        else:
            pass
        return queryset


class PowertrainPushRecords(APIView):
    # 设置默认的每页默认数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="zone",
                required=False,
                location="query",
                schema=coreschema.String(description="区域"),
            ),
            Field(
                name="module",
                required=False,
                location="query",
                schema=coreschema.String(description="工段/模块"),
            ),
            Field(
                name="station",
                required=False,
                location="query",
                schema=coreschema.String(description="工位"),
            ),
            Field(
                name="proj_name",
                required=False,
                location="query",
                schema=coreschema.String(description="测点名称"),
            ),
            Field(
                name="alarm_date",
                required=False,
                location="query",
                schema=coreschema.String(description="报警日期"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = PowerEphmPushRecords_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 获取数据集合的逻辑
        queryset = PowerEphmPushRecords.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        module = request.query_params.get("module")
        station = request.query_params.get("station")
        proj_name = request.query_params.get("proj_name")
        alarm_date = request.query_params.get("alarm_date")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if module is not None:
            queryset = queryset.filter(module=module)
        if station is not None:
            queryset = queryset.filter(station=station)
        if proj_name is not None:
            queryset = queryset.filter(projname=proj_name)
        if alarm_date is not None:
            queryset = queryset.filter(alarm_time__contains=alarm_date)
        else:
            pass
        return queryset


class PowertrainPushRecordsCount(APIView):
    # 设置默认的每页默认数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="zone",
                required=False,
                location="query",
                schema=coreschema.String(description="区域"),
            ),
            Field(
                name="module",
                required=False,
                location="query",
                schema=coreschema.String(description="工段/模块"),
            ),
            Field(
                name="station",
                required=False,
                location="query",
                schema=coreschema.String(description="工位"),
            ),
            Field(
                name="proj_name",
                required=False,
                location="query",
                schema=coreschema.String(description="测点名称"),
            ),
            Field(
                name="alarm_date",
                required=False,
                location="query",
                schema=coreschema.String(description="报警日期"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_grouped_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = PowerEphmPushRecordsCount_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_grouped_queryset(self, request, *args, **kwargs):
        # 这里实现获取分组数据集合的逻辑
        # 使用 annotate 和 Count 函数进行分组统计，同时使用 Max 函数获取最新的 alarm_time
        queryset = (
            PowerEphmPushRecords.objects.values("zone", "module", "station", "projname")
            .annotate(count=Count("id"), latest_alarm_time=Max("alarm_time"), latest_alarm_value=Max("alarm_value"), upper_limit=Max("upper_limit"), lower_limit=Min("lower_limit"))  # 新增  # 新增
            .order_by("zone", "module", "station", "projname")
        )

        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        module = request.query_params.get("module")
        station = request.query_params.get("station")
        alarm_date = request.query_params.get("alarm_date")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if module is not None:
            queryset = queryset.filter(module=module)
        if station is not None:
            queryset = queryset.filter(station=station)
        if alarm_date is not None:
            queryset = queryset.filter(alarm_time__contains=alarm_date)

        return queryset


class PowertrainMeasurementPointLimitUpdate(APIView):
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=True,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="upper_limit",
                required=True,
                location="query",
                schema=coreschema.String(description="上限"),
            ),
            Field(
                name="lower_limit",
                required=True,
                location="query",
                schema=coreschema.String(description="下限"),
            ),
        ]
    )

    def put(self, request, *args, **kwargs):
        # 获取请求的参数
        id = request.query_params.get("id")
        upper_limit = request.query_params.get("upper_limit")
        lower_limit = request.query_params.get("lower_limit")
        print(id, upper_limit, lower_limit)
        try:
            obj = PowerEphmMeasurementPointLedger.objects.get(id=id)
        except ObjectDoesNotExist:
            return Response({"error": "Object with given id does not exist"}, status=status.HTTP_404_NOT_FOUND)
        if upper_limit is not None:
            obj.upper_limit = upper_limit
        if lower_limit is not None:
            obj.lower_limit = lower_limit
        obj.save()
        s = PowerEphmMeasurementPointLedger_Serializer(instance=obj)
        return Response(s.data, status=status.HTTP_200_OK)


class PowertrainQdasFeatureQuery(APIView):
    # 设置默认的每页默认数据量
    page_size = 1000
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="station",
                required=False,
                location="query",
                schema=coreschema.String(description="工位"),
            ),
            Field(
                name="model",
                required=False,
                location="query",
                schema=coreschema.String(description="机型检具"),
            ),
            Field(
                name="feature",
                required=False,
                location="query",
                schema=coreschema.String(description="测量特征"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = EphmQdasBlockFeature_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 获取数据集合的逻辑
        queryset = EphmQdasBlockFeature.objects.filter().order_by("teil")
        # 获取请求的参数
        station = request.query_params.get("station")
        model = request.query_params.get("model")
        feature = request.query_params.get("feature")
        # 根据参数是否存在添加不同筛选条件
        if station is not None:
            queryset = queryset.filter(wvauftrag=station)
        if model is not None:
            queryset = queryset.filter(tebezeich__contains=model)
        if feature is not None:
            queryset = queryset.filter(memerkbez__contains=feature)
        else:
            pass
        return queryset


# ephm_limits表视图
class EphmLimitsCustomSchema(AutoSchema):
    """
    自定义的Schema类，用于处理EphmLimits相关的序列化逻辑。

    这个类继承自AutoSchema，并根据需要重写或添加方法以处理特定的序列化需求。

    示例用法：
    schema = EphmLimitsCustomSchema()
    serialized_data = schema.dump(data)
    """

    def get_manual_fields(self, path, method):
        # 获取父类中已有的手动字段
        manual_fields = super().get_manual_fields(path, method)

        if method.lower() == "get":
            # 为 GET 请求添加查询参数
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="query",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="item",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="测点"),
                ),
                Field(
                    name="item_cn",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="测点中文名"),
                ),
                Field(
                    name="item_level",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="测点等级"),
                ),
                Field(
                    name="up_limit",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="上限"),
                ),
                Field(
                    name="low_limit",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="下限"),
                ),
                Field(name="changetime", required=False, location="query", schema=coreschema.String(description="修改日期时间(例如:2025-01-16 16:39:01)")),
                # 更多查询参数...
            ]
        elif method.lower() == "post":
            # 为 POST 请求设置必填项和其他选项
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="form",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="item",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点"),
                ),
                Field(
                    name="item_cn",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点中文名"),
                ),
                Field(
                    name="item_level",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点等级"),
                ),
                Field(
                    name="up_limit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="上限"),
                ),
                Field(
                    name="low_limit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="下限"),
                ),
            ]
        elif method.lower() == "patch":
            manual_fields = [
                Field(
                    name="id",
                    required=True,
                    location="form",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="item",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点"),
                ),
                Field(
                    name="item_cn",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点中文名"),
                ),
                Field(
                    name="item_level",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点等级"),
                ),
                Field(
                    name="up_limit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="上限"),
                ),
                Field(
                    name="low_limit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="下限"),
                ),
            ]
        elif method.lower() == "delete":
            manual_fields = [
                Field(
                    name="id",
                    required=True,
                    location="query",
                    schema=coreschema.Number(description="id"),
                )
            ]
        return manual_fields


class EphmLimitsView(APIView):
    """
    类说明：
        用于处理ephm_limits表的数据，可以使用get，post，patch，delete方法
    方法：
        get:获取数据
        post:添加数据
        patch:部分更新数据
        delete:删除数据
    """

    # 设置默认的每页默认数据量
    page_size = 100000
    # 设置在API DOC的字段显示
    schema = EphmLimitsCustomSchema()

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = EphmLimits_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        request.data["changetime"] = datetime.now()
        serializer = EphmLimits_Serializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, *args, **kwargs):
        id = request.data["id"]
        try:
            instance = EphmLimits.objects.get(id=id)
        except ObjectDoesNotExist:
            return Response({"error": "Object does not exist"}, status=404)

        serializer = EphmLimits_Serializer(instance, data=request.data, partial=True)
        if serializer.is_valid():
            instance.changetime = datetime.now()
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=400)

    def delete(self, request, *args, **kwargs):
        id = request.query_params.get("id")
        try:
            instance = EphmLimits.objects.get(id=id)
            instance.delete()
            return Response({"message": "删除成功！"}, status=status.HTTP_200_OK)
        except ObjectDoesNotExist:
            return Response({"error": "Object does not exist"}, status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = EphmLimits.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        op = request.query_params.get("op")
        item = request.query_params.get("item")
        item_cn = request.query_params.get("item_cn")
        item_level = request.query_params.get("item_level")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if op is not None:
            queryset = queryset.filter(op=op)
        if item is not None:
            queryset = queryset.filter(item=item)
        if item_cn is not None:
            queryset = queryset.filter(item_cn=item_cn)
        if item_level is not None:
            queryset = queryset.filter(item_level=item_level)
        else:
            pass
        return queryset


# ephm_limits_warning表视图
class EphmLimitsWarningCustomSchema(AutoSchema):
    """
    自定义的Schema类，用于处理EphmLimitsWarning相关的序列化逻辑。

    这个类继承自AutoSchema，并根据需要重写或添加方法以处理特定的序列化需求。

    """

    def get_manual_fields(self, path, method):
        # 获取父类中已有的手动字段
        manual_fields = super().get_manual_fields(path, method)

        if method.lower() == "get":
            # 为 GET 请求添加查询参数
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="query",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="item",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="测点"),
                ),
                Field(
                    name="item_cn",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="测点中文名"),
                ),
                Field(
                    name="item_level",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="测点等级"),
                ),
                Field(
                    name="value",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="超限报警值"),
                ),
                Field(
                    name="up_limit",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="上限"),
                ),
                Field(
                    name="low_limit",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="下限"),
                ),
                Field(
                    name="measures",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="措施"),
                ),
                Field(
                    name="person_in_charge",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="负责人"),
                ),
                Field(
                    name="start_time",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="开始日期时间，格式示例：2024-07-01 16:34:42"),
                ),
                Field(
                    name="end_time",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="结束日期时间，格式示例：2024-07-10 16:34:42"),
                ),
                # 更多查询参数...
            ]
        elif method.lower() == "post":
            # 为 POST 请求设置必填项和其他选项
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="form",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="item",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点"),
                ),
                Field(
                    name="item_cn",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点中文名"),
                ),
                Field(
                    name="item_level",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点等级"),
                ),
                Field(
                    name="value",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="超限报警值"),
                ),
                Field(
                    name="up_limit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="上限"),
                ),
                Field(
                    name="low_limit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="下限"),
                ),
                Field(
                    name="ephm_measures",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="措施"),
                ),
                Field(
                    name="person_in_charge",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="负责人"),
                ),
            ]
        elif method.lower() == "patch":
            manual_fields = [
                Field(
                    name="id",
                    required=True,
                    location="form",
                    schema=coreschema.Number(description="id"),
                ),
                Field(
                    name="zone",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="区域"),
                ),
                Field(
                    name="op",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="工位号"),
                ),
                Field(
                    name="item",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点"),
                ),
                Field(
                    name="item_cn",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点中文名"),
                ),
                Field(
                    name="item_level",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="测点等级"),
                ),
                Field(
                    name="value",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="超限报警值"),
                ),
                Field(
                    name="up_limit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="上限"),
                ),
                Field(
                    name="low_limit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="下限"),
                ),
                Field(
                    name="ephm_measures",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="措施"),
                ),
                Field(
                    name="person_in_charge",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="负责人"),
                ),
            ]
        elif method.lower() == "delete":
            manual_fields = [
                Field(
                    name="id",
                    required=True,
                    location="query",
                    schema=coreschema.Number(description="id"),
                )
            ]
        return manual_fields


class EphmLimitsWarningView(APIView):
    """
    类说明：
        用于处理ephm_limits_warning表的数据，可以使用get，post，patch，delete方法
    方法：
        get:获取数据
        post:添加数据
        patch:部分更新数据
        delete:删除数据
    """

    # 设置默认的每页默认数据量
    page_size = 100000
    # 设置在API DOC的字段显示
    schema = EphmLimitsWarningCustomSchema()

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = EphmLimitsWarning_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        request.data["timestamp"] = datetime.now()
        request.data["create_time"] = datetime.now()
        request.data["update_time"] = datetime.now()
        serializer = EphmLimitsWarning_Serializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, *args, **kwargs):
        id = request.data["id"]
        try:
            instance = EphmLimitsWarning.objects.get(id=id)
        except ObjectDoesNotExist:
            return Response({"error": "Object does not exist"}, status=404)
        request.data["update_time"] = datetime.now()
        serializer = EphmLimitsWarning_Serializer(instance, data=request.data, partial=True)
        if serializer.is_valid():
            instance.update_time = datetime.now()
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=400)

    def delete(self, request, *args, **kwargs):
        id = request.query_params.get("id")
        try:
            instance = EphmLimitsWarning.objects.get(id=id)
            instance.delete()
            return Response({"message": "删除成功！"}, status=status.HTTP_200_OK)
        except ObjectDoesNotExist:
            return Response({"error": "Object does not exist"}, status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = EphmLimitsWarning.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        zone = request.query_params.get("zone")
        op = request.query_params.get("op")
        item = request.query_params.get("item")
        item_cn = request.query_params.get("item_cn")
        ephm_measures = request.query_params.get("ephm_measures")
        person_in_charge = request.query_params.get("person_in_charge")
        item_level = request.query_params.get("item_level")
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if zone is not None:
            queryset = queryset.filter(zone=zone)
        if op is not None:
            queryset = queryset.filter(op=op)
        if item is not None:
            queryset = queryset.filter(item=item)
        if item_cn is not None:
            queryset = queryset.filter(item_cn=item_cn)
        if item_level is not None:
            queryset = queryset.filter(item_level=item_level)
        if ephm_measures is not None:
            queryset = queryset.filter(ephm_measures__contains=ephm_measures)
        if person_in_charge is not None:
            queryset = queryset.filter(person_in_charge__contains=person_in_charge)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(timestamp__gte=start_time_param_trans, timestamp__lte=end_time_param_trans)
        else:
            pass
        return queryset


class ToleranceCacheSchema(AutoSchema):
    """
    自定义 AutoSchema 为 ToleranceCacheView 生成接口文档
    """

    def get_manual_fields(self, path, method):
        # 调用基类的 AutoSchema 生成默认字段
        manual_fields = super().get_manual_fields(path, method)
        method = method.lower()
        if method == "delete":
            # 为 DELETE 请求手动添加请求体字段
            manual_fields = [
                Field(
                    name="description",
                    required=False,
                    location="body",
                    schema=coreschema.String(description="清空公差表缓存"),
                )
            ]
        elif method == "put":
            # 为 PUT 请求手动添加请求体字段
            manual_fields = [
                Field(
                    name="json_data",
                    required=False,
                    location="body",
                    schema=coreschema.String(description='JSON 数据，格式: {"zone": "指定区域", "op": "指定工位", "item": "指定项目"}，不填则更新全部数据'),
                )
            ]

        return manual_fields


class ToleranceCacheView(APIView):
    schema = ToleranceCacheSchema()

    def delete(self, request):
        """
        清空公差表缓存,当后续使用时,会从数据库重新导入到Redis缓存。
        """
        clear_tolerance_cache()
        return Response({"status": "公差表缓存清空完成！"}, status=status.HTTP_200_OK)

    def put(self, request):
        """
        更新指定区域/工位/测点公差表缓存
        """
        try:
            # 检查 request.data 的类型
            if isinstance(request.data, str):
                try:
                    data = json.loads(request.data)
                except json.JSONDecodeError:
                    return Response({"status": "failed", "message": "请求体不是有效的JSON格式"}, status=status.HTTP_400_BAD_REQUEST)
            else:
                data = request.data
                print(data, type(data))

            zone = data.get("zone")
            op = data.get("op")
            item = data.get("item")
            success = update_tolerance_cache(zone, op, item)
            if success:
                return Response({"status": "success"}, status=status.HTTP_200_OK)
            else:
                return Response({"status": "failed", "message": "未找到符合条件的记录"}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({"status": "failed", "message": f"发生其他错误: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class EphmLimitsWarningDeleteAllView(APIView):
    """
    类说明：
        用于批量删除ephm_limits_warning表的全部数据，可以使用delete方法，谨慎调用！！！
    """

    def delete(self, request, *args, **kwargs):
        EphmLimitsWarning.objects.all().delete()
        return Response({"message": "全部删除成功!"}, status=status.HTTP_200_OK)
